/*********************************************************************************
 *      Copyright:  (C) 2021 ljl
 *                  All rights reserved.
 *
 *       Filename:  server.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2021年11月30日)
 *         Author:  Li Jiale <244871365@qq.com>
 *      ChangeLog:  1, Release initial version on "2021年11月30日 19时07分11秒"
 *                 
 ********************************************************************************/

#include "cJSON.h"
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <time.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <syslog.h>
#include <getopt.h>
#include <libgen.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>
#include "sqlite3.h"

#define MAX_EVENTS 512
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))

void print_usage(char *progname);
int socket_server_init(char *listen_ip, int listen_port);
void set_socket_rlimit(void);
void sigstop(int signum);
int open_sqlite(sqlite3 **db);

int main(int argc,char *argv[])
{
    int                 listenfd;
    int                 clifd;
    int                 opt;
    int                 serv_port;
    int                 i;
    char                *data;
    cJSON               *json,*json_id,*json_time,*json_temper;
    char                *progname;
    int                 rv;
    char                buf[1024];
    int                 found;
    sqlite3             *db=NULL;
    int                 len;
    int                 nrow=0;
    int                 ncolumn = 0;
    char                *zErrMsg =NULL;
    char                **azResult=NULL;
    int                 delete_seq = 0;
    FILE                *stderr;
    char                sql2[256];

    int                 count = 0;

    int                 epollfd;
    struct epoll_event  event;
    struct epoll_event  event_array[MAX_EVENTS];
    int                 events;

    struct option       long_options[]=
    {
        {"port", required_argument, NULL, 'p'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };

    progname = basename(argv[0]);

    while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1)
    {
        switch (opt)
        {
            case'p':
                serv_port = atoi(optarg);
                break;

            case'h':
                print_usage(progname);
                return EXIT_SUCCESS;

            default:
                break;
        }
    }

    if( !serv_port )
    {
        print_usage(progname);
        return -1;
    }
    
    signal(SIGUSR1,sigstop);

    //daemon(0,0);

    if( open_sqlite(&db) < 0 )
    {
        printf("open sqlite3 failure\n");
        return -8;
    }

    openlog("server.c",LOG_CONS | LOG_PID,0);

    set_socket_rlimit();

    if( (listenfd=socket_server_init(NULL, serv_port)) < 0 )
    {
        printf("ERROR: %s server listen on port %d failure\n", argv[0],serv_port);
        syslog(LOG_WARNING,"ERROR: %s server listen on port %d failure\n", argv[0],serv_port);
        return -2;
    }

    if( (epollfd=epoll_create(MAX_EVENTS)) < 0 )
    {
        syslog(LOG_WARNING,"epoll_create() failure: %s\n", strerror(errno));
        return -3;
    }

    event.events = EPOLLIN;
    event.data.fd = listenfd;

    if( epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event) < 0)
    {
        printf("epoll add listen socket failure: %s\n", strerror(errno));
        syslog(LOG_WARNING,"epoll add listen socket failure: %s\n", strerror(errno));
        return -4;
    }
    
    for ( ; ; )
    {
        events = epoll_wait(epollfd, event_array, MAX_EVENTS, -1);
        if(events < 0)
        {
            printf("epoll failure: %s\n", strerror(errno));
            syslog(LOG_WARNING,"epoll failure: %s\n", strerror(errno));
            break;
        }
        else if(events == 0)
        {
            printf("epoll get timeout\n");
            syslog(LOG_WARNING,"epoll get timeout\n");
            continue;
        }
        for(i=0; i<events; i++)
        {
            if ( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) )
            {
                printf("epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno));
                syslog(LOG_WARNING,"epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno));
                epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                close(event_array[i].data.fd);
            }
            if( event_array[i].data.fd == listenfd )
            {
                if( (clifd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0)
                {
                    printf("accept new client failure: %s\n", strerror(errno));
                    syslog(LOG_WARNING,"accept new client failure: %s\n", strerror(errno));
                    continue;
                }
                event.data.fd = clifd;
                event.events = EPOLLIN;
                if( epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &event) < 0 )
                {
                    printf("epoll add client socket failure: %s\n", strerror(errno));
                    syslog(LOG_WARNING,"epoll add client socket failure: %s\n", strerror(errno));
                    close(event_array[i].data.fd);
                    continue;
                }
            }
            else
            {
                memset(buf, 0, sizeof(buf));
                if( (rv=read(event_array[i].data.fd, buf, sizeof(buf))) <= 0)
                {
                    printf("socket[%d] read failure or get disconncet and will be removed.\n",event_array[i].data.fd);
                    syslog(LOG_WARNING,"socket[%d] read failure or get disconncet and will be removed.\n",event_array[i].data.fd);
                    epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                    close(event_array[i].data.fd);
                    continue;
                }
                else
                {

                    data = buf;

                   // while(1)
                    //{

                        json = cJSON_Parse(data);
                        json_id = cJSON_GetObjectItem( json , "id" );
                        json_temper = cJSON_GetObjectItem( json , "temperature");
                        json_time = cJSON_GetObjectItem( json , "tiem");
                    

                        printf("%s\n",buf);


                        if(json_id == NULL || json_temper == NULL || json_time == NULL)
                        {   printf("NULL\n");
                            break;
                        }

                        memset(sql2,0,sizeof(sql2));
                        snprintf(sql2,sizeof(sql2),"INSERT INTO 'TemperData' VALUES(NULL,\"%s\",\"%s\",\"%s\")",json_id->valuestring,json_temper->valuestring,json_time->valuestring);
                        
                        sqlite3_exec(db,sql2,NULL,NULL,&zErrMsg);
                    
                    //}
                    cJSON_Delete(json);
                }
            }
        }
    }
    sqlite3_close(db);
    closelog();
    close(listenfd);
    return 0;
}

void print_usage(char *progname)
{
    printf("Usage: %s [OPTION]...\n", progname);
    printf(" %s is a socket server program, which used to verify client and echo back string from it\n",progname);
    printf("\nMandatory arguments to long options are mandatory for short options too:\n");

    printf(" -p[port ] Socket server port address\n");
    printf(" -h[help ] Display this help information\n");
    printf("\nExample: %s -b -p 8900\n", progname);
    return;
}

int open_sqlite(sqlite3 **db)
{
    int             len;
    char            *zErrMsg =NULL;
    FILE            *stderr;

    len = sqlite3_open("temper.db",db);
    if( len )
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(*db));
        sqlite3_close(*db);
        return -1;
    }
    
    char *sql = " CREATE TABLE IF NOT EXISTS TemperData(\
                 GUD INTEGER PRIMARY KEY AUTOINCREMENT,\
                 ID VARCHAR(50),\
                 TEMPER VARCHAR(50),\
                 TIME VARCHAR(50)\
                 );";

    sqlite3_exec(*db,sql,NULL,NULL,&zErrMsg);

    return 0;
}


int socket_server_init(char *listen_ip, int listen_port)
{
    struct sockaddr_in  servaddr;
    int                 rv = 0;
    int                 on = 1;
    int                 listenfd;

    if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("Use socket() to create a TCP socket failure: %s\n", strerror(errno));
        syslog(LOG_WARNING,"Use socket() to create a TCP socket failure: %s\n", strerror(errno));
        return -1;
    }

    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(listen_port);

    if( !listen_ip ) 
    {
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    }
    else
    {
        if (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0)
        {
            printf("inet_pton() set listen IP address failure.\n");
            syslog(LOG_WARNING,"inet_pton() set listen IP address failure.\n");
            rv = -2;
            goto CleanUp;
        }
    }

    if(bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
    {
        printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        syslog(LOG_WARNING,"Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -3;
        goto CleanUp;
    }

    if(listen(listenfd, 64) < 0)
    {
        printf("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        syslog(LOG_WARNING,"Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -4;
        goto CleanUp;
    }

CleanUp:
    if( rv < 0 )
    {
        close(listenfd);
    }
    else
    {
        rv = listenfd;
    }
    return rv;
}

void set_socket_rlimit(void)
{
    struct rlimit limit = {0};
    getrlimit(RLIMIT_NOFILE, &limit );
    limit.rlim_cur = limit.rlim_max;
    setrlimit(RLIMIT_NOFILE, &limit );
}

void sigstop(int signum)
{
    if(signum == SIGUSR1)
    {
        syslog(LOG_EMERG,"server is closed,process quit now!\n");
        closelog();
        exit(0);
    }
}












